package com.cloud.pikachu.dingtalk.service.token;

import com.alibaba.fastjson.JSONObject;
import com.cloud.pikachu.dingtalk.api.TokenAPI;
import com.cloud.pikachu.dingtalk.bean.common.AccessToken;
import com.cloud.pikachu.dingtalk.constant.DingtalkConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * access token管理service
 */
@Service
public class AccessTokenService {
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenService.class);
    private AccessTokenData accessTokenData = new AccessTokenData();

    /**
     * 用用获取token
     * @return
     */
    public String getAccessToken(){
        Date nowDate = new Date();

        if(accessTokenData.getAccessToken()==null ||
                accessTokenData.getCreateTimestamp()== 0L ||
                (nowDate.getTime() - accessTokenData.getCreateTimestamp()) > 7200*1000){
            getApi();
        }

        return accessTokenData.getAccessToken();
    }

    /**
     * 强制刷新accesstoken值
     * @return
     */
    String updateAccessToken(){
        getApi();
        return accessTokenData.getAccessToken();
    }

    public void getApi(){
        AccessToken accessToken = TokenAPI.accessToken(DingtalkConstant.corpid , DingtalkConstant.CorpSecret);
        if(accessToken.getErrcode()==0){
            accessTokenData.setAccessToken(accessToken.getAccess_token());
            accessTokenData.setCreateTimestamp(System.currentTimeMillis());
        }else{
            logger.error("获取accessToken失败，钉钉返回数据["+ JSONObject.toJSONString(accessToken) +"]");
        }
    }
}
